package com.sqx.modules.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserBrowseDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserBrowse;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.coupon.dao.TbCouponUserDao;
import com.sqx.modules.coupon.entity.TbCouponUser;
import com.sqx.modules.errand.dao.TbIndentDao;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsShopRelevancyDao;
import com.sqx.modules.goods.dao.GoodsSkuDao;
import com.sqx.modules.goods.entity.*;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.order.dao.AppOrderDao;
import com.sqx.modules.order.dao.EvaluateDao;
import com.sqx.modules.order.dao.OrderGoodsDao;
import com.sqx.modules.order.entity.Evaluate;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.pay.service.WxErrService;
import com.sqx.modules.sys.dao.SysUserRoleDao;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.fieYun.FeiYunUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class AppAppOrderServiceImpl extends ServiceImpl<AppOrderDao, TbOrder> implements AppOrderService {

    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private GoodsSkuDao goodsSkuDao;
    @Autowired
    private TbCouponUserDao tbCouponUserDao;
    @Autowired
    private AppOrderService appOrderService;
    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private GoodsShopRelevancyDao goodsShopRelevancyDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private WxErrService wxErrService;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private EvaluateDao evaluateDao;
    @Autowired
    private TbIndentService tbIndentService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private TbIndentDao tbIndentDao;
    @Autowired
    private UserBrowseDao userBrowseDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Override
    public Result insertOrder(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            return addOrder(userId, shopId, goodsId, num, skuId, skuMessage, orderType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Transactional
    public Result addOrder(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        //先判断该商品的库存是否足够
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>().eq("shop_id", shopId).eq("goods_id", goodsId));
        if (goodsShopRelevancy.getInventory() < num) {
            return Result.error("该商品库存不足！");
        }
        TbOrder order = new TbOrder();
        order = appOrderDao.selectOne(new QueryWrapper<TbOrder>()
                .eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        Goods goods = goodsDao.selectById(goodsId);
        UserEntity userEntity = userDao.selectById(userId);
        TbOrder tbOrder = new TbOrder();
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (order == null) {
            tbOrder.setUserId(userId);
            tbOrder.setUserName(userEntity.getUserName());
            tbOrder.setPhone(userEntity.getPhone());
            tbOrder.setOrderNumber(getGeneralOrder());
            tbOrder.setIsPay(0);
            tbOrder.setDeleteFlag(0);
            tbOrder.setStatus(1);
            tbOrder.setShopId(shopId);
            //创建订单，订单发起人就是该登录用户
            tbOrder.setParentUserId(userId);
            tbOrder.setCreateTime(format);
            tbOrder.setAddGoodsTime(format);
            appOrderDao.insertOrder(tbOrder);

            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(tbOrder.getOrderId());
            tbOrder1.setParentId(tbOrder.getOrderId());
            appOrderDao.updateById(tbOrder1);
            //添加订单-商品表
            Long orderId = tbOrder.getOrderId();
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(orderId);
            orderGoods.setGoodsName(goods.getGoodsName());
            orderGoods.setSkuId(skuId);
            GoodsSku goodsSku = goodsSkuDao.selectById(skuId);
            orderGoods.setGoodsPrice(goodsSku.getSkuPrice());
            orderGoods.setSkuMessage(skuMessage);
            orderGoods.setGoodsNum(num);
            orderGoods.setGoodsPack(goods.getPackMoney());
            orderGoods.setGoodsPicture(goods.getGoodsCover());
            orderGoods.setGoodsId(goods.getGoodsId());
            orderGoods.setUserId(userId);
            orderGoodsDao.insert(orderGoods);
        } else {
            //添加订单-商品表
            Long orderId = order.getOrderId();
            OrderGoods orderGoods = orderGoodsDao.selectOne(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("goods_id", goods.getGoodsId()).eq("sku_id", skuId));
            if(orderGoods!=null){
                orderGoods.setGoodsNum(orderGoods.getGoodsNum()+1);
                orderGoodsDao.updateById(orderGoods);
            }else{
                orderGoods = new OrderGoods();
                orderGoods.setOrderId(orderId);
                orderGoods.setGoodsName(goods.getGoodsName());
                orderGoods.setSkuId(skuId);
                GoodsSku goodsSku = goodsSkuDao.selectById(skuId);
                orderGoods.setGoodsPrice(goodsSku.getSkuPrice());
                orderGoods.setSkuMessage(skuMessage);
                orderGoods.setGoodsNum(num);
                orderGoods.setGoodsPack(goods.getPackMoney());
                orderGoods.setGoodsPicture(goods.getGoodsCover());
                orderGoods.setGoodsId(goods.getGoodsId());
                orderGoods.setUserId(userId);
                orderGoodsDao.insert(orderGoods);
            }
            //修改订单表最后一次添加商品的时间
            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(orderId);
            tbOrder1.setAddGoodsTime(format);
            appOrderDao.updateById(tbOrder1);
        }
        return Result.success();
    }


    @Override
    public Result shareTheBill(Long userId, Long shopId) {
        TbOrder tbOrder2 = appOrderDao.selectOne(new QueryWrapper<TbOrder>()
                .eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        if (tbOrder2 == null) {
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            UserEntity userEntity = userDao.selectById(userId);
            TbOrder tbOrder = new TbOrder();
            tbOrder.setUserId(userId);
            tbOrder.setUserName(userEntity.getUserName());
            tbOrder.setPhone(userEntity.getPhone());
            tbOrder.setOrderNumber(getGeneralOrder());
            tbOrder.setIsPay(0);
            tbOrder.setDeleteFlag(0);
            tbOrder.setStatus(1);
            tbOrder.setShopId(shopId);
            //创建订单，订单发起人就是该登录用户
            tbOrder.setParentUserId(userId);
            tbOrder.setCreateTime(format);
            tbOrder.setAddGoodsTime(format);
            appOrderDao.insertOrder(tbOrder);
            Long orderId = tbOrder.getOrderId();
            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(tbOrder.getOrderId());
            tbOrder1.setParentId(tbOrder.getOrderId());
            appOrderDao.updateById(tbOrder1);
            return Result.success().put("data", orderId);
        }
        return Result.success().put("data", tbOrder2.getOrderId());
    }

    @Override
    public Result selectShareTheBill(Long userId, Long orderId) {
        HashMap hashMap = new HashMap();
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        if (tbOrder == null) {
            return Result.success();
        }
        List<OrderGoods> parentShareTheBill = orderGoodsDao.selectParentShareTheBill(orderId, tbOrder.getUserId());
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectShareTheBill(orderId, tbOrder.getUserId());
        GoodsShop goodsShop = goodsShopDao.selectById(tbOrder.getShopId());
        hashMap.put("parentShareTheBill", parentShareTheBill);
        hashMap.put("orderGoodsList", orderGoodsList);
        hashMap.put("goodsShop", goodsShop);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result deleteByGoods(Long userId, Long id) {
        orderGoodsDao.delete(new QueryWrapper<OrderGoods>().eq("id", id).eq("user_id", userId));
        return Result.success();
    }

    @Override
    public Result deleteShareTheBill(Long userId, Long orderId) {
        orderGoodsDao.delete(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("user_id", userId));
        return Result.success();
    }

    @Override
    public Result deleteOrder(Long userId, Long orderId) {
        appOrderDao.delete(new QueryWrapper<TbOrder>().eq("user_id", userId).eq("order_id", orderId));
        return Result.success();
    }

    @Override
    public Result joinOrder(Long userId, Long orderId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage) {
        //先判断该商品的库存是否足够
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                .eq("shop_id", shopId).eq("goods_id", goodsId));
        if (goodsShopRelevancy.getInventory() < num) {
            return Result.error("该商品库存不足！");
        }
        Goods goods = goodsDao.selectById(goodsId);
        OrderGoods orderGoods = orderGoodsDao.selectOne(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("goods_id", goods.getGoodsId()).eq("sku_id", skuId).eq("user_id", userId));
        if(orderGoods!=null){
           orderGoods.setGoodsNum(orderGoods.getGoodsNum()+1);
           orderGoodsDao.updateById(orderGoods);
        }else{
            //添加订单-商品表
            orderGoods = new OrderGoods();
            orderGoods.setOrderId(orderId);
            orderGoods.setGoodsName(goods.getGoodsName());
            orderGoods.setSkuId(skuId);
            orderGoods.setGoodsPrice(goods.getGoodsMoney());
            orderGoods.setSkuMessage(skuMessage);
            orderGoods.setGoodsNum(num);
            orderGoods.setGoodsPack(goods.getPackMoney());
            orderGoods.setGoodsPicture(goods.getGoodsCover());
            orderGoods.setGoodsId(goods.getGoodsId());
            orderGoods.setUserId(userId);
            orderGoodsDao.insert(orderGoods);
        }

        return Result.success();
    }


    @Transactional
    @Override
    public Result buyGoods(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        //先判断该商品的库存是否足够
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>().eq("shop_id", shopId).eq("goods_id", goodsId));
        if (goodsShopRelevancy.getInventory() < num) {
            return Result.error("该商品库存不足！");
        }
        Goods goods = goodsDao.selectById(goodsId);
        UserEntity userEntity = userDao.selectById(userId);
        TbOrder tbOrder = new TbOrder();
        tbOrder.setUserId(userId);
        tbOrder.setUserName(userEntity.getUserName());
        tbOrder.setPhone(userEntity.getPhone());
        tbOrder.setOrderNumber(getGeneralOrder());
        tbOrder.setIsPay(0);
        tbOrder.setDeleteFlag(0);
        tbOrder.setStatus(2);
        tbOrder.setShopId(shopId);
        //创建订单，订单发起人就是该登录用户
        tbOrder.setParentUserId(userId);
        //   tbOrder.setPackMoney(goods.getPackMoney());
        //  tbOrder.setOrderType(orderType);
        tbOrder.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        /*if (orderType == 2) {
            CommonInfo one = commonInfoService.findOne(123);
            Double value = Double.valueOf(one.getValue());
            tbOrder.setErrandMoney(BigDecimal.valueOf(value));
        }*/
        appOrderDao.insertOrder(tbOrder);

        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderId(tbOrder.getOrderId());
        orderGoods.setGoodsName(goods.getGoodsName());
        orderGoods.setSkuId(skuId);
        GoodsSku goodsSku = goodsSkuDao.selectById(skuId);
        orderGoods.setGoodsPrice(goodsSku.getSkuPrice());
        orderGoods.setSkuMessage(skuMessage);
        orderGoods.setGoodsNum(num);
        orderGoods.setGoodsPack(goods.getPackMoney());
        orderGoods.setGoodsPicture(goods.getGoodsCover());
        orderGoods.setGoodsId(goods.getGoodsId());
        orderGoods.setUserId(userId);
        orderGoodsDao.insert(orderGoods);

        BigDecimal multiply = orderGoods.getGoodsPrice().multiply(new BigDecimal(num));
        TbOrder tbOrder1 = new TbOrder();
        tbOrder1.setOrderId(tbOrder.getOrderId());
        tbOrder1.setParentId(tbOrder.getOrderId());
        tbOrder1.setPayMoney(multiply);
        appOrderDao.updateById(tbOrder1);
        return Result.success().put("data", tbOrder.getOrderId());
    }

    @Override
    public Result echoOrder(Long userId, Long shopId, Long goodsId) {
        TbOrder tbOrder = appOrderDao.selectOne(new QueryWrapper<TbOrder>().eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        if (tbOrder == null) {
            return Result.error("用户在该商铺没有订单");
        }
        Long orderId = tbOrder.getOrderId();
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("goods_id", goodsId));
        return Result.success().put("data", orderGoodsList);
    }




    /*public Result insertOrder1(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        //判断该用户在该商店有没有订单，没有的话创建订单，有的话加入订单
        List<TbOrder> tbOrder1 = appOrderDao.selectList(new QueryWrapper<TbOrder>()
                .eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));

        if(tbOrder1==null) {
            Goods goods = goodsDao.selectById(goodsId);
            UserEntity userEntity = userDao.selectById(userId);
            net.sf.json.JSONObject goodsJson = net.sf.json.JSONObject.fromObject(goods);

            TbOrder order = new TbOrder();
            order.setUserId(userId);
            order.setUserName(userEntity.getUserName());
            order.setPhone(userEntity.getPhone());
            order.setOrderNumber(getGeneralOrder());
            order.setIsPay(0);
            order.setDeleteFlag(0);
            order.setStatus(1);
        //    order.setNum(num);
            order.setShopId(shopId);
            //创建订单，订单发起人就是该登录用户
            order.setParentUserId(userId);
            order.setPackMoney(goods.getPackMoney());
            order.setOrderType(orderType);
            order.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            if (orderType == 2) {
                CommonInfo one = commonInfoService.findOne(121);
                Double value = Double.valueOf(one.getValue());
                order.setErrandMoney(BigDecimal.valueOf(value));
            }
            appOrderDao.insertOrder(order);
            TbOrder tbOrder = new TbOrder();
            tbOrder.setOrderId(order.getOrderId());
            tbOrder.setParentId(order.getOrderId());
            appOrderDao.updateById(tbOrder);
        }
        return Result.success();
    }*/


    @Override
    public TbOrder selectOrderByNum(String orderNum) {
        TbOrder tbOrder = appOrderDao.selectOne(new QueryWrapper<TbOrder>().eq("order_number", orderNum));
        return tbOrder;
    }

    @Override
    public Result selectAllOrder(Integer page, Integer limit, Integer status, String phone, Long shopId, String userName, String orderNumber, Integer orderType, String shopName) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.selectOrder(pages, status, phone, shopId, userName, orderNumber, orderType, shopName);
        for (int i = 0; i < tbOrderIPage.getRecords().size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", tbOrderIPage.getRecords().get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
            //todo
            BigDecimal packMoney = BigDecimal.valueOf(0);
            for (int a = 0; a < orderGoodsList.size(); a++) {
                packMoney = packMoney.add(tbOrderIPage.getRecords().get(i).getPackMoney());
            }
            tbOrderIPage.getRecords().get(i).setPackMoney(packMoney);
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }


    @Override
    public Result selectAllOrderAdmin(Integer page, Integer limit, Integer status, String phone, Long shopId, String userName, String orderNumber, Integer orderType, String shopName,String riderPhone) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.selectAllOrderAdmin(pages, status, phone, shopId, userName, orderNumber, orderType, shopName,riderPhone);
        for (int i = 0; i < tbOrderIPage.getRecords().size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", tbOrderIPage.getRecords().get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
            //todo
            BigDecimal packMoney = BigDecimal.valueOf(0);
            for (int a = 0; a < orderGoodsList.size(); a++) {
                if (tbOrderIPage.getRecords().get(i).getPackMoney() != null) {
                    packMoney = packMoney.add(tbOrderIPage.getRecords().get(i).getPackMoney());
                }
            }
            tbOrderIPage.getRecords().get(i).setPackMoney(packMoney);
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectOrderByUserId(Long userId, String date, String dateType) {
        HashMap hashMap = new HashMap();
        int count = appOrderDao.selectCountOrderByUserId(userId, date, dateType);
        BigDecimal bigDecimal = appOrderDao.selectSunMoneyByUserId(userId, date, dateType);
        hashMap.put("bigDecimal", bigDecimal);
        hashMap.put("count", count);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectOrderDetails(Integer page, Integer limit, Long userId) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.selectOrderDetails(pages, userId);
        for (int i = 0; i < tbOrderIPage.getRecords().size(); i++) {
            Long orderId = tbOrderIPage.getRecords().get(i).getOrderId();
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
        }


        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result waitTakeFood(Long userId, Integer orderType, Integer page, Integer limit, Integer status) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.waitTakeFood(pages, userId, orderType, status);
        List<TbOrder> records = tbOrderIPage.getRecords();
        int size = records.size();
        for (int i = 0; i < size; i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", records.get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public List<TbOrder> selectOrderByParentId(Long parentId) {
        List<TbOrder> tbOrder = appOrderDao.selectList(new QueryWrapper<TbOrder>().eq("parent_id", parentId));
        return tbOrder;
    }

    @Override
    public Result selectOrderById(Long orderId) {
        TbOrder tbOrder = appOrderDao.selectByOrderId(orderId);
        int i = appOrderDao.selectCountOrderByTime(tbOrder.getPayTime(), tbOrder.getShopId());
        tbOrder.setCountOrder(i);
        if (tbOrder.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
            tbOrder.setCouponMoney(tbCouponUser.getMoney());
        }
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
        tbOrder.setOrderGoodsList(orderGoodsList);
        return Result.success().put("data", tbOrder);
    }

    @Override
    public TbOrder selectOrderByIds(Long orderId) {
        TbOrder tbOrder = appOrderDao.selectByOrderId(orderId);
        int i = appOrderDao.selectCountOrderByTime(tbOrder.getPayTime(), tbOrder.getShopId());
        tbOrder.setCountOrder(i);
        if (tbOrder.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
            tbOrder.setCouponMoney(tbCouponUser.getMoney());
        }
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
        tbOrder.setOrderGoodsList(orderGoodsList);
        GoodsShop goodsShop = goodsShopDao.selectById(tbOrder.getShopId());
        if (goodsShop != null) {
            tbOrder.setShopName(goodsShop.getShopName());
        }
        return tbOrder;
    }


    @Transactional
    @Override
    public Result updateGoodsNum(Long orderGoodsId, Integer type, Integer num, Long shopId) {
        /*reentrantReadWriteLock.writeLock().lock();
        try{*/
        //type = 1增加商品数  = 2 减少商品数

        OrderGoods orderGoods = orderGoodsDao.selectById(orderGoodsId);
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                .eq("shop_id", shopId)
                .eq("goods_id", orderGoods.getGoodsId()));

        if (type == 1 && goodsShopRelevancy.getInventory() <= orderGoods.getGoodsNum()) {
            return Result.error("该商品库存不足，不能再添加商品！");
        }
        if (type == 1) {
            OrderGoods orderGoods1 = new OrderGoods();
            orderGoods1.setId(orderGoodsId);
            orderGoods1.setGoodsNum(orderGoods.getGoodsNum() + num);
            orderGoodsDao.updateById(orderGoods1);
        } else {
            if (orderGoods.getGoodsNum() <= 1) {
                orderGoodsDao.deleteById(orderGoodsId);
            } else {
                OrderGoods orderGoods2 = new OrderGoods();
                orderGoods2.setId(orderGoodsId);
                orderGoods2.setGoodsNum(orderGoods.getGoodsNum() - num);
                orderGoodsDao.updateById(orderGoods2);
            }
        }
        /*}catch (Exception e){
            e.printStackTrace();
            log.error("减少购物车商品出错："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }*/
        return Result.success();
    }

    @Override
    public Result emptyShoppingTrolley(Long userId, Long shopId) {
        appOrderDao.delete(new QueryWrapper<TbOrder>().eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        return Result.success();
    }

    @Override
    public Result employCoupon(Long userId, Long parentId, Long couponId) {
        TbOrder tbOrder = appOrderDao.selectById(parentId);
        TbCouponUser tbCouponUser = tbCouponUserDao.selectById(couponId);

        TbOrder tbOrder1 = new TbOrder();
        tbOrder1.setOrderId(tbOrder.getOrderId());
        tbOrder1.setCouponId(tbCouponUser.getId());
        appOrderDao.updateById(tbOrder1);
        return Result.success();
    }

    @Override
    public Result deleteCouponByOrderId(Long orderId) {
        appOrderDao.deleteCouponByOrderId(orderId);
        return Result.success();
    }

    @Override
    public Result print(Long orderId) {
        TbOrder tbOrder = selectOrderByIds(orderId);
        Long shopId = tbOrder.getShopId();
        GoodsShop goodsShop = goodsShopDao.selectById(shopId);
        if (StringUtils.isNotEmpty(goodsShop.getSnCode())) {
            FeiYunUtils.print(goodsShop.getSnCode(), null, tbOrder);
        } else {
            return Result.error("当前商家未绑定打印机！");
        }
        return Result.success();
    }

    @Transactional
    public Result updateOrders(TbOrder order){
        String format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbOrder tbOrder = selectOrderByIds(order.getOrderId());
        if (order.getStatus() == 6) {
            if (tbOrder.getStatus().equals(6)) {
                return Result.success();
            }
            //商家接单
            order.setShopReceivingTime(format1);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum1 = tbOrder.getOrderNumber();
            msgList.add("商家已接单");
            msgList.add(orderNum1);
            msgList.add(shopName);
            msgList.add(format1);
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            userService.pushToSingle("商家已接单", "亲爱的用户您好，商家已接单，请耐心等待！", userEntity.getClientid());

            //计算商户应得金额
            CommonInfo one1 = commonInfoService.findOne(300);
            Double aDouble = 1 - Double.valueOf(one1.getValue());
            BigDecimal sumMoney=tbOrder.getPayMoney();
            if(tbOrder.getCouponId()!=null ){
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                sumMoney=tbOrder.getPayMoney().add(tbCouponUser.getMoney());
            }
            if (tbOrder.getAutoSendOrder() == 0) {
                //再减去商户需要支付的配送费
                sumMoney = sumMoney.subtract(tbOrder.getErrandMoney());
            }

            Double shopMoney = sumMoney.doubleValue() * aDouble;
            shopMoney = (BigDecimal.valueOf(shopMoney).setScale(2, BigDecimal.ROUND_DOWN)).doubleValue();
            tbOrder.setShopIncomeMoney(BigDecimal.valueOf(shopMoney));

            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            if (StringUtils.isNotEmpty(goodsShop.getSnCode())) {
                FeiYunUtils.print(goodsShop.getSnCode(), null, tbOrder);
            }
        } else if (order.getStatus() == 3) {
            if (tbOrder.getStatus().equals(3)) {
                return Result.success();
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setTitle("餐品制作完成");
            if (tbOrder.getOrderType() == 1) {
                messageInfo.setContent("您的餐品已制作完成，请及时取餐");
            } else if (tbOrder.getOrderType() == 2) {
                messageInfo.setContent("您的餐品已制作完成，正在配送中");
                //如果是外卖订单,则修改外卖订单的状态
                GoodsShop goodsShop = goodsShopDao.selectById(tbOrder.getShopId());
                if (goodsShop.getAutoSendOrder() == 0) {
                    TbIndent tbIndent = tbIndentDao.selectOne(new QueryWrapper<TbIndent>().eq("order_id", tbOrder.getOrderId()));
                    TbIndent tbIndent1 = new TbIndent();
                    tbIndent1.setIndentId(tbIndent.getIndentId());
                    tbIndent1.setCreateTime(format1);
                    tbIndent1.setIndentState("2");
                    tbIndentService.updateById(tbIndent1);
                }
            }
            messageInfo.setCreateAt(format1);
            messageInfo.setUserId(tbOrder.getUserId().toString());
            messageInfoDao.insert(messageInfo);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum1 = tbOrder.getOrderNumber();
            /*msgList.add(shopName);
            msgList.add(orderNum1);
            msgList.add("已制作完成");
            msgList.add(format1);*/

            msgList.add("已制作完成");
            msgList.add(orderNum1);
            msgList.add(shopName);
            msgList.add(format1);
            /*
            if(tbOrder.getOrderType()==1){
                msgList.add("您的餐品已制作完成，请及时取餐");
            }else if(tbOrder.getOrderType()==2){
                msgList.add("您的餐品已制作完成，正在配送中");
            }*/
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            userService.pushToSingle("制作完成", "亲爱的用户您好，您的订单已制作完成，请耐心等待配送！", userEntity.getClientid());
        } else if (order.getStatus() == 4) {
            if (tbOrder.getStatus().equals(4)) {
                return Result.success();
            }
            appOrderService.accomplishOrder(order.getOrderId());
            //管理端完成订单，则消息通知用户
            //添加消息记录
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setTitle("订单完成");
            messageInfo.setContent("您的订单已完成，欢迎下次光临");
            messageInfo.setCreateAt(format1);
            messageInfo.setUserId(tbOrder.getUserId().toString());
            messageInfoDao.insert(messageInfo);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum1 = tbOrder.getOrderNumber();
            msgList.add("订单完成");
            msgList.add(orderNum1);
            msgList.add(shopName);
            msgList.add(format1);
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            userService.pushToSingle("订单完成", "亲爱的用户您好，您的订单已完成，欢迎下次光临！", userEntity.getClientid());
        } else if (order.getStatus() == 8) {
            if (tbOrder.getStatus().equals(8)) {
                return Result.success();
            }
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            //已支付判断支付方式
            if (tbOrder.getPayType() == 2) {
                //余额支付，直接退还钱包
                userMoneyDao.updateMayMoney(1, tbOrder.getUserId(), tbOrder.getPayMoney().doubleValue());
            } else if(tbOrder.getPayType()==1){
                //微信支付调支付退款接口
                PayDetails payDetails = new PayDetails();
                payDetails.setOrderId(tbOrder.getOrderNumber());
                payDetails.setType(3);
                payDetails.setMoney(tbOrder.getPayMoney().doubleValue());
                boolean b = wxErrService.wxRefund(payDetails);
                if(!b){
                    return Result.error("退款失败，请联系客服！");
                }
            }else{
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                String code = AliPayController.alipayRefund(payDetails);
                if(StringUtils.isNotBlank(code)){
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if(!"10000".equals(code1)){
                        return Result.error("退款失败！"+alipay_trade_refund_response.getString("sub_msg"));
                    }
                }else{
                    return Result.error("退款失败！");
                }
            }
            tbOrder.setStatus(5);
            appOrderDao.updateById(tbOrder);
            //添加退款记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            userMoneyDetails.setTitle("退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());
            userMoneyDetails.setContent("商家拒绝接单，退款到账：" + tbOrder.getPayMoney() + "元，退款按原路返回");
            userMoneyDetails.setCreateTime(format1);
            userMoneyDetailsDao.insert(userMoneyDetails);
            //判断是否使用优惠券
            if(tbOrder.getCouponId()!=null){
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                tbCouponUser.setStatus(0);
                tbCouponUserDao.updateById(tbCouponUser);
            }


            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(266);
            List<String> msgList = new ArrayList<>();
            msgList.add(tbOrder.getOrderNumber());
            msgList.add("商家拒绝接单订单");
            msgList.add(tbOrder.getPayMoney().toString());
            msgList.add(format1);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
            userService.pushToSingle("下单失败", "抱歉，商家已拒绝接单，给您带来不便请谅解，如有疑问可联系客服！", userEntity.getClientid());

            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
            for(int a = 0;a<orderGoodsList.size();a++){
                OrderGoods orderGoods = orderGoodsList.get(a);
                Integer goodsNum =orderGoods .getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", tbOrder.getShopId()).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales()-goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory()+goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(2,goodsNum, goodsShopRelevancy.getShopId());
            }

            return Result.success("取消订单成功！");
        }
        order.setUpdateTime(format1);
        baseMapper.updateById(order);
        return Result.success();
    }


    @Override
    public Result updateOrder(TbOrder order) {
        reentrantReadWriteLock.writeLock().lock();
        try{
            return updateOrders(order);
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改订单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }


    @Transactional
    @Override
    public Result accomplishOrder(Long orderId) {
        reentrantReadWriteLock.writeLock().lock();
        try{
            return accomplishOrders(orderId);
        }catch (Exception e){
            e.printStackTrace();
            log.error("完成订单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }



    @Transactional
    @Override
    public Result accomplishOrders(Long orderId) {
        TbOrder tbOrder2 = appOrderDao.selectById(orderId);
        if (tbOrder2.getStatus().equals(4)) {
            return Result.success();
        }
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (tbOrder2.getAutoSendOrder() != null && tbOrder2.getAutoSendOrder().equals(0)) {
            TbIndent indent = tbIndentService.getOne(new QueryWrapper<TbIndent>().eq("order_id", orderId));
            if (indent == null || !"4".equals(indent.getIndentState())) {
                return Result.error("请等待骑手送达！");
            }
            tbOrder2.setStatus(4);
            appOrderDao.updateById(tbOrder2);
            //修改跑腿订单的状态和给骑手佣金
            indent.setIndentState("6");
            indent.setFinishTime( DateUtils.format(new Date()));
            tbIndentService.updateById(indent);
            tbIndentService.finshIndent(tbOrder2.getUserId(), indent.getIndentNumber());
        }else{
            if (tbOrder2.getStatus().equals(4)) {
                return Result.success();
            }

            tbOrder2.setStatus(4);
            appOrderDao.updateById(tbOrder2);
        }


        GoodsShop goodsShop1 = goodsShopDao.selectById(tbOrder2.getShopId());
        //计算商户应得金额
        CommonInfo one1 = commonInfoService.findOne(300);
        Double aDouble = 1 - Double.valueOf(one1.getValue());
        BigDecimal sumMoney=tbOrder2.getPayMoney();
        BigDecimal couponMoney=BigDecimal.ZERO;
        if(tbOrder2.getCouponId()!=null ){
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder2.getCouponId());
            sumMoney=tbOrder2.getPayMoney().add(tbCouponUser.getMoney());
            couponMoney=tbCouponUser.getMoney();
        }

        BigDecimal errandMoney=BigDecimal.ZERO;
        if (tbOrder2.getAutoSendOrder()!=null && tbOrder2.getAutoSendOrder() == 0 && goodsShop1.getErrandMoney() != null && goodsShop1.getErrandMoney().doubleValue() > 0) {
            //再减去商户需要支付的配送费
            sumMoney = sumMoney .subtract( goodsShop1.getErrandMoney());
            errandMoney=goodsShop1.getErrandMoney();
        }
        Double shopMoney = sumMoney.doubleValue() * aDouble;

        shopMoney = (BigDecimal.valueOf(shopMoney).setScale(2, BigDecimal.ROUND_DOWN)).doubleValue();
        BigDecimal pingRate=sumMoney.subtract(BigDecimal.valueOf(shopMoney));
        TbOrder tbOrder3 = new TbOrder();
        tbOrder3.setOrderId(orderId);
        tbOrder3.setShopIncomeMoney(BigDecimal.valueOf(shopMoney));
        appOrderDao.updateById(tbOrder3);
        //添加商户用户钱包收入记录
        UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails();
        userMoneyDetails1.setShopId(goodsShop1.getShopId());
        userMoneyDetails1.setTitle("商户订单收入，订单号："+tbOrder2.getOrderNumber());
//        userMoneyDetails1.setContent("商户本单收入金额：" + shopMoney + "元");
        userMoneyDetails1.setContent("用户实付金额:"+tbOrder2.getPayMoney()+",跑腿费:"+errandMoney+",商品总金额:"+sumMoney+",平台扣除:"+pingRate+"，优惠券面值:"+couponMoney);
        userMoneyDetails1.setType(1);
        userMoneyDetails1.setClassify(3);
        userMoneyDetails1.setMoney(BigDecimal.valueOf(shopMoney));
        userMoneyDetails1.setCreateTime(format);
        userMoneyDetails1.setState(2);
        userMoneyDetailsDao.insert(userMoneyDetails1);
        //将用户支付的金额转入商户用户钱包
        userMoneyService.updateMoney(1, goodsShop1.getUserId(), shopMoney);
        //管理端完成订单，则消息通知用户
        //添加消息记录
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setTitle("订单完成");
        messageInfo.setContent("您的订单已完成，欢迎下次光临");
        messageInfo.setCreateAt(format);
        messageInfo.setUserId(tbOrder.getUserId().toString());
        messageInfoDao.insert(messageInfo);
        //设置小程序消息推送
        CommonInfo one = commonInfoService.findOne(269);
        List<String> msgList = new ArrayList<>();
        Long shopId = tbOrder.getShopId();
        GoodsShop goodsShop = goodsShopDao.selectById(shopId);
        String shopName = goodsShop.getShopName();
        String orderNum1 = tbOrder.getOrderNumber();
        msgList.add("订单完成");
        msgList.add(orderNum1);
        msgList.add(shopName);
        msgList.add(format);
        UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
        userService.pushToSingle("订单完成", "亲爱的用户你好，您的订单已完成，欢迎下次光临！", userEntity.getClientid());
        return Result.success();
    }

    // 自动完成超时订单
    //@Scheduled(cron = "0 */1 * * * ?")
    public void orderEnd() {
        CommonInfo one = commonInfoService.findOne(268);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(one.getValue()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(calendar.getTime());
        List<TbOrder> tbOrders = appOrderDao.selectOrderByTimeList(date);
        //将所有超时订单改成已完成
        appOrderDao.updateorderStatus(date);
        for (int i = 0; i < tbOrders.size(); i++) {
            //管理端完成订单，则消息通知用户
            //添加消息记录
            TbOrder tbOrder = appOrderDao.selectById(tbOrders.get(i).getOrderId());
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(5));
            messageInfo.setTitle("订单完成");
            messageInfo.setContent("您的订单已完成，欢迎下次光临");
            messageInfo.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            messageInfo.setUserId(tbOrder.getUserId().toString());
            messageInfoDao.insert(messageInfo);
            //设置小程序消息推送
            CommonInfo one1 = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum1 = tbOrder.getOrderNumber();
            msgList.add("订单完成");
            msgList.add(orderNum1);
            msgList.add(shopName);
            msgList.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one1.getValue(), msgList, 1);
            userService.pushToSingle("订单完成", "亲爱的用户您好，您的订单已完成，欢迎下次光临！", userEntity.getClientid());
        }

    }

    @Transactional
    @Override
    public Result insertEvaluate(Evaluate evaluate) {
        evaluate.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        evaluateDao.insert(evaluate);
        TbOrder tbOrder = new TbOrder();
        tbOrder.setCommentFlag(1);
        appOrderDao.update(tbOrder, new QueryWrapper<TbOrder>().eq("order_number", evaluate.getOrderNumber()));
        //重新计算并修改该商铺评分
        Evaluate evaluate1 = evaluateDao.selectScoreByShopId(evaluate.getShopId());
        Double score = evaluate1.getAllScore() / Double.valueOf(evaluate1.getEvaluatecount());
        GoodsShop goodsShop = new GoodsShop();
        goodsShop.setShopId(evaluate.getShopId());
        goodsShop.setShopScore(score);
        goodsShopDao.updateById(goodsShop);
        return Result.success();
    }

    @Override
    public Result selectShoppingTrolley(Long userId) {
        List<TbOrder> tbOrderIPage = appOrderDao.selectShoppingTrolley(userId);
        for (int i = 0; i < tbOrderIPage.size(); i++) {
            Long orderId = tbOrderIPage.get(i).getOrderId();
            List<OrderGoods> orderGoods = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
            tbOrderIPage.get(i).setOrderGoodsList(orderGoods);
        }
        return Result.success().put("data", tbOrderIPage);
    }

    @Override
    public Result selectShoppingTrolleyByShopId(Long userId, Long shopId) {
        TbOrder tbOrders = appOrderDao.selectShoppingTrolleyByShopId(userId, shopId);
        List<OrderGoods> orderGoods = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrders.getOrderId()));
        tbOrders.setOrderGoodsList(orderGoods);
        return Result.success().put("data", tbOrders);
    }

    @Transactional
    @Override
    public Result userCancelOrder(Long orderId) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        if (tbOrder.getStatus().equals(5)) {
            return Result.success();
        }
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, -1);
        Date parse = null;
        if (tbOrder.getStatus() == 6) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                parse = sdf.parse(tbOrder.getShopReceivingTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if ((tbOrder.getStatus() == 6 && parse.getTime() > cal.getTime().getTime()) || (tbOrder.getStatus() == 7)) {
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            //已支付判断支付方式

            if (tbOrder.getPayType() == 2) {
                //余额支付，直接退还钱包
                userMoneyDao.updateMayMoney(1, tbOrder.getUserId(), tbOrder.getPayMoney().doubleValue());
            } else if(tbOrder.getPayType()==1){
                //微信支付调支付退款接口
                PayDetails payDetails = new PayDetails();
                payDetails.setOrderId(tbOrder.getOrderNumber());
                payDetails.setType(3);
                payDetails.setMoney(tbOrder.getPayMoney().doubleValue());
                boolean b = wxErrService.wxRefund(payDetails);
                if(!b){
                    return Result.error("退款失败，请联系客服！");
                }
            }else{
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                String code = AliPayController.alipayRefund(payDetails);
                if(StringUtils.isNotBlank(code)){
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if(!"10000".equals(code1)){
                        return Result.error("退款失败！"+alipay_trade_refund_response.getString("sub_msg"));
                    }
                }else{
                    return Result.error("退款失败！");
                }
            }
            tbOrder.setStatus(5);
            appOrderDao.updateById(tbOrder);
            //添加退款记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            userMoneyDetails.setTitle("退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());
            userMoneyDetails.setContent("退款到账：" + tbOrder.getPayMoney() + "元，退款按原路返回");
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsDao.insert(userMoneyDetails);
            //判断是否使用优惠券
            if(tbOrder.getCouponId()!=null){
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                tbCouponUser.setStatus(0);
                tbCouponUserDao.updateById(tbCouponUser);
            }
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(266);
            List<String> msgList = new ArrayList<>();
            msgList.add(tbOrder.getOrderNumber());
            msgList.add("用户取消订单");
            msgList.add(tbOrder.getPayMoney().toString());
            msgList.add(format);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
            userService.pushToSingle("取消订单", "您已取消订单！", userEntity.getClientid());


            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
            for(int a = 0;a<orderGoodsList.size();a++){
                OrderGoods orderGoods = orderGoodsList.get(a);
                Integer goodsNum =orderGoods .getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", tbOrder.getShopId()).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales()-goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory()+goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(2,goodsNum, goodsShopRelevancy.getShopId());
            }

            return Result.success("取消订单成功！");
        }
        return Result.error("餐品正在制作中，无法退款！");
    }

    @Override
    public Result shopReplyEvaluate(String orderNumber, String shopReplyMessage) {
        Evaluate evaluate = new Evaluate();
        evaluate.setShopReplyMessage(shopReplyMessage);
        evaluateDao.update(evaluate, new QueryWrapper<Evaluate>().eq("order_number", orderNumber));
        return Result.success();
    }


    @Transactional
    @Override
    public Result deleteOrderList(List<Integer> orderId) {
        for (int i = 0; i < orderId.size(); i++) {
            baseMapper.deleteById(orderId.get(i));
        }
        return Result.success();
    }

    @Override
    public Result selectBuyGoods(Long userId, Long orderId) {
        //   TbOrder tbOrder = appOrderDao.selectOne(new QueryWrapper<TbOrder>().eq("order_id", orderId).eq("user_id", userId));
        TbOrder tbOrder = appOrderDao.selectBuyGoods(orderId, userId);
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
        tbOrder.setOrderGoodsList(orderGoodsList);
        return Result.success().put("data", tbOrder);
    }

    @Transactional
    @Override
    public Result adminCancelOrder(Long orderId) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        if (tbOrder.getIsPay() == 0) {
            //未支付直接取消
            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(orderId);
            tbOrder1.setStatus(5);
            appOrderDao.updateById(tbOrder1);
        } else {
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            //已支付判断支付方式
            if (tbOrder.getPayType() == 2) {
                //余额支付，直接退还钱包
                userMoneyDao.updateMayMoney(1, tbOrder.getUserId(), tbOrder.getPayMoney().doubleValue());
            } else if(tbOrder.getPayType()==1){
                //微信支付调支付退款接口
                PayDetails payDetails = new PayDetails();
                payDetails.setOrderId(tbOrder.getOrderNumber());
                payDetails.setType(3);
                payDetails.setMoney(tbOrder.getPayMoney().doubleValue());
                boolean b = wxErrService.wxRefund(payDetails);
                if(!b){
                    return Result.error("退款失败，请联系客服！");
                }
            }else{
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                String code = AliPayController.alipayRefund(payDetails);
                if(StringUtils.isNotBlank(code)){
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if(!"10000".equals(code1)){
                        return Result.error("退款失败！"+alipay_trade_refund_response.getString("sub_msg"));
                    }
                }else{
                    return Result.error("退款失败！");
                }
            }
            tbOrder.setStatus(5);
            appOrderDao.updateById(tbOrder);
            //取消跑腿订单
            TbIndent tbIndent = new TbIndent();
            TbIndent tbIndent1 = tbIndentDao.selectOne(new QueryWrapper<TbIndent>().eq("order_id", orderId));
            tbIndent.setIndentId(tbIndent1.getIndentId());
            tbIndent.setIndentState("10");
            tbIndentDao.updateById(tbIndent);
            //添加退款记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            userMoneyDetails.setTitle("退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());
            userMoneyDetails.setContent("退款到账：" + tbOrder.getPayMoney() + "元，退款按原路返回");
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsDao.insert(userMoneyDetails);
            //判断是否使用优惠券
            if(tbOrder.getCouponId()!=null){
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                tbCouponUser.setStatus(0);
                tbCouponUserDao.updateById(tbCouponUser);
            }
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(266);
            List<String> msgList = new ArrayList<>();
            msgList.add(tbOrder.getOrderNumber());
            msgList.add("门店主动取消订单");
            msgList.add(tbOrder.getPayMoney().toString());
            msgList.add(format);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
            userService.pushToSingle("下单失败", "亲爱的用户您好，商铺已取消您的订单，给您带来不便请谅解，如有疑问可联系客服！", userEntity.getClientid());

            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
            for(int a = 0;a<orderGoodsList.size();a++){
                Integer goodsNum = orderGoodsList.get(a).getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", tbOrder.getShopId()).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales()-goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory()+goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(2,goodsNum, goodsShopRelevancy.getShopId());
            }
        }
        return Result.success();
    }


    @Override
    public Result selectOrderList(Long userId, Long shopId, Integer status, Integer orderType, Integer page, Integer limit) {
        HashMap hashMap = new HashMap();
        Page<TbOrder> pages = new Page(page, limit);
        IPage<TbOrder> tbOrderList = baseMapper.selectOrderList(pages, userId, status, orderType, shopId);
        BigDecimal money = new BigDecimal(0);
        ArrayList list = new ArrayList();
        for (int i = 0; i < tbOrderList.getRecords().size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", tbOrderList.getRecords().get(i).getOrderId()));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                BigDecimal goodsPrice = orderGoodsList.get(a).getGoodsPrice();
                Integer goodsNum = orderGoodsList.get(a).getGoodsNum();
                BigDecimal multiply = goodsPrice.multiply(new BigDecimal(goodsNum));
                money = money.add(multiply);
            }
            list.add(orderGoodsList);
            tbOrderList.getRecords().get(i).setOrderGoodsList(list);
        }
        if (shopId != null && userId != null) {
            reentrantReadWriteLock.writeLock().lock();
            try {
                UserBrowse userBrowse = userBrowseDao.selectOne(new QueryWrapper<UserBrowse>().eq("user_id", userId).eq("by_browse_id", shopId));
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                if (userBrowse != null) {
                    userBrowse.setUpdateTime(format);
                } else {
                    userBrowse = new UserBrowse();
                    userBrowse.setUserId(userId);
                    userBrowse.setByBrowseId(shopId);
                    userBrowse.setUpdateTime(format);
                    userBrowseDao.insert(userBrowse);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reentrantReadWriteLock.writeLock().unlock();
            }
        }
        PageUtils pageUtils = new PageUtils(tbOrderList);
        hashMap.put("pageUtils", pageUtils);
        hashMap.put("money", money);
        return Result.success().put("data", hashMap);
    }

    public String getGeneralOrder() {
        Date date = new Date();
        String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format + newString;
    }
}
